<template>
  <section class="upload-info-type-table">
    <header class="top-line">
      <div>
      <!-- 顶部按钮组 -->
        <template v-if="!isCheckStatus">
          <el-button
            size="small"
            @click="showOnly"
            icon="el-icon-plus"
            type="primary"
          >
            批量报税
          </el-button>
          <el-button
            size="small"
            @click="refresh"
            icon="el-icon-refresh"
            type="primary"
          >
            刷新
          </el-button>
        </template>

        <template v-if="isCheckStatus">
          <el-button
            @click="checkBilles"
            type="primary"
            size="small"
            id="checkBillesBtn"
          >
            确认
          </el-button>
          <el-button
            @click="showAll"
            type="primary"
            size="small"
            plain
          >
            返回
          </el-button>
        </template>
      </div>
      <div class="search-section">
        <el-input
          placeholder="请输入公司名称进行查询"
          v-model="searchParams.bName"
          @keyup.enter.native="search"
          @clear="search"
          size="mini"
          suffix-icon="el-icon-search"
          clearable
        >
        </el-input>
        <div>
          <el-select
            v-model="searchParams.incomeTaxStatus"
            @change="search"
            @clear="search"
            clearable
            size="mini"
            placeholder="报税状态"
          >
            <el-option
              v-for="item in oneKeyBillStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
    </header>
    <el-table
      ref="multipleTable"
      stripe
      :data="tableData || []"
      :empty-text="tableData === null ? '加载中...' : '暂无数据'"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="70" v-if="isCheckStatus">
        <template #header>
          <el-checkbox
            v-model="checkedAll"
            @change="checkedAllChange"
            :indeterminate="isIndeterminate"
            class="checked-all"
          >
          </el-checkbox>
        </template>
        <template slot-scope="scope">
          <el-checkbox
            v-model="checkedList[scope.$index]"
            @change="checkedChange"
          >
          </el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="编号" width="160">
        <template slot-scope="scope">
          <span class="tag-serial">{{ scope.row.id }}</span>
          <el-tag v-if="scope.row.perManageDealName" type="danger">{{scope.row.perManageDealName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cName" label="公司名称">
      </el-table-column>
      <el-table-column prop="businessLicenseNumber" label="社会信用代码">
      </el-table-column>
      <el-table-column prop="password" label="税务局密码"> </el-table-column>
      <el-table-column
        prop="mobile"
        label="税务局用户名/预留电话号码"
      >
      </el-table-column>
      <el-table-column prop="statusIndex" label="报税状态">
        <template slot-scope="scope">
          <el-tooltip
            v-if="scope.row.statusIndex === 15"
            class="item"
            placement="bottom"
          >
            <div slot="content">
              报税失败可能是因为账号、密码错误、或尚未抄报税。<br />请退出页面后重新尝试。若多次尝试失败，则需人工处理
            </div>
            <span class="error-status"
              >{{ oneKeyBillStatusObj[scope.row.statusIndex] }}
              <i class="el-icon-warning-outline"></i
            ></span>
          </el-tooltip>

          <template v-else>
            {{ oneKeyBillStatusObj[scope.row.statusIndex] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="330">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.statusIndex === 20"
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click.native="onEditIncomingTax(scope.row)"
          >
            查看所得税情况
          </el-button>
          <el-button
            slot="reference"
            v-if="[22, 23].indexOf(scope.row.statusIndex) !== -1"
            type="success"
            icon="el-icon-edit"
            size="mini"
            @click.native="onEdit(scope.row)"
          >
            查看缴纳结果
          </el-button>
           <el-popover
            v-if="[29].indexOf(scope.row.statusIndex) !== -1"
            placement="top-start"
            title="失败原因"
            width="200"
            trigger="click"
            :content="getFailReason(scope.row)">
          <el-button
            slot="reference"
            type="success"
            icon="el-icon-edit"
            size="mini"
          >
            查看失败原因
          </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      class="pagination"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      @current-change="currentPageChange"
    >
    </el-pagination>
  </section>
</template>

<script>
import { oneKeyBillStatusList, oneKeyBillStatusObj } from "@/components/map";
import { delObjNullKey } from "@/components/utiles";

export default {
  components: {},
  props: {
    type: {
      type: Number,
    },
  },
  data() {
    return {
      isCheckStatus: false,
      checkedAll: false,
      isIndeterminate: false,
      checkedList: [],
      total: 0,
      tableData: null,
      currentPage: 1,
      pageSize: 20,
      oneKeyBillStatusList,
      oneKeyBillStatusObj,
      searchParams: {
        incomeTaxStatus: "",
        bName: "",
      },
      indeterminate: false,
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    onForcePay(data) {
      this.$http.post("/companies/forcePayTaxes", {
        bizId: data.id,
        payTaxType: this.type,
      }).then((res) => {
        if(res.code != 0) return;
        this.refresh();
      })
    },
    checkedChange(val, index) {
      this.checkedList[index] = val;
      const allLen = this.tableData.length;
      const checkedLen = this.checkedList.filter((v) => v).length;

      this.checkedAll = checkedLen === allLen;
      this.isIndeterminate = checkedLen ? checkedLen !== allLen : false;
    },
    checkedAllChange(val) {
      if (val) {
        const checkedList = this.tableData.map(
          (v, i) => v.statusIndex === 20 || v.statusIndex === 22
        );
        this.checkedList = checkedList;
        this.checkedAll = !!checkedList.length;
      } else {
        this.checkedList = this.checkedList.map((v) => false);
        this.checkedAll = false;
      }
      this.isIndeterminate = false;
    },
    checkBilles() {
      // 选中数据
      const data = this.tableData.filter((v, i) => this.checkedList[i]);

      if (data.length === 0) {
        this.$message({
          message: "请至少选择一条",
          type: "warning",
        });
        return;
      }

      this.$http.post("/incomeTax/batchDeclare", {
        bizIdList: data.map(v => v.id),
        type: this.type,
      }).then((res) => {
        if(res.code != 0) return;
        this.refresh()
      })
    },
    loadData(isReset = false) {
      const { searchParams, pageSize, currentPage } = this;
      const params = {
        ...searchParams,
        type: this.type,
        size: pageSize,
        pageNumber: isReset ? 1 : currentPage,
      };
      this.$http.get("/incomeTax/list", { params }).then((res) => {
        if (isReset) {
          this.currentPage = 1;
        }
        const {code, data} = res;
        if(code != 0) return;
        
        if(!data || !data.list) {
          this.total = 0;
          this.resetChecked([]);
          this.tableData = [];
        }else{
          this.total = res.data.totalNumber;
          this.resetChecked(res.data.list);
          this.tableData = res.data.list;
        }
      });
    },
    resetChecked(list) {
      this.checkedList = list.map((v) => false);
      this.checkedAll = false;
      this.isIndeterminate = false;
    },
    currentPageChange() {
      this.loadData();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    onEdit(data) {
      // localStorage.setItem("valueAddedTaxDetail", JSON.stringify(data));
      this.$router.push({
        name: "valueAddedTaxDetail",
      });
    },
    // 查看所得税情况
    onEditIncomingTax(data) {
      this.$router.push({
        name: "peopleManageDetail",
        query: {
          bizId: data.id,
          cName: data.cName
        }
      });
    },
    /**
     * 批量核对
     */
    checkMany() {
      this.isCheckStatus = !this.isCheckStatus;
    },
    showOnly() {
      this.checkMany();
      this.tableData = this.tableData.filter(
          (v, i) => v.statusIndex === 20 || v.statusIndex === 22
        );
    },
    showAll() {
       this.checkMany();
       this.loadData();
    },
    refresh() {
      this.loadData(true);
    },
    search(e) {
      this.$nextTick(() => {
        this.refresh();
      });
    },
    onEdit(data) {
      localStorage.setItem("valueAddedTaxDetail", JSON.stringify(data));
      this.$router.push({
        name: "checkTaxReportResult",
      });
    },
     getFailReason(data) {
      this.$http
        .get("/incomeTax/getDeclareTaxesImageMsg", {
          params: {
            bizId: data.id,
            taxType: data.taxType,
            imageType: data.imageType
          },
        })
        .then((res) => {
          if (res.code == 0) {
            return res.data.imageData
          }
        });
      
    },
  },
};
</script>

<style lang="less" scoped>
.upload-info-type-table {
  padding: 0 10px;
  .top-line {
    padding-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }
  .pagination {
    text-align: right;
    padding: 20px 0 0;
  }
}

.search-section {
  display: flex;
}

.error-status {
  color: #ff0000;
}
.tag-serial {
    margin-right: 10px;
  }
</style>
